/*
============================================================================
 Name        : C$(Basename)AppUi from $(Basename)Appui.cpp
 Author      : $(Author)
 Version     :
 Copyright   : $(Copyright)
 Description : C$(Basename)AppUi implementation
============================================================================
*/

// INCLUDE FILES
#include "$(Basename)Application.h"
#include "$(Basename)Appui.h"
#include "$(Basename)View.h"
#include "$(Basename)View2.h"
#include <$(Basename).rsg>
#include "$(Basename).hrh"

#include <stringloader.h>
#include <f32file.h>
#include <bautils.h>
#include <charconv.h>
#include <hlplch.h>
#include <avkon.hrh>
#include <aknmessagequerydialog.h>

#include "$(Basename)_$(uid).hlp.hrh"

// ================= MEMBER FUNCTIONS =======================
//
// ----------------------------------------------------------
// C$(Basename)AppUi::ConstructL()
// 
// ----------------------------------------------------------
//
void C$(Basename)AppUi::ConstructL()
	{
	BaseConstructL();


	// Show tabs for main views from resources
	CEikStatusPane* sp = StatusPane();

	// Fetch pointer to the default navi pane control
	iNaviPane = (CAknNavigationControlContainer*)sp->ControlL( 
		TUid::Uid(EEikStatusPaneUidNavi));

	// Tabgroup has been read from resource and it were pushed to the navi pane. 
	// Get pointer to the navigation decorator with the ResourceDecorator() function. 
	// Application owns the decorator and it has responsibility to delete the object.
	iDecoratedTabGroup = iNaviPane->ResourceDecorator();
	if (iDecoratedTabGroup)
		{
		iTabGroup = (CAknTabGroup*) iDecoratedTabGroup->DecoratedControl();
$if(series60!=1.x)
		iTabGroup->SetObserver( this );
$endif()
		}

	C$(Basename)View* view1 = new (ELeave) C$(Basename)View;

	CleanupStack::PushL( view1 );
	view1->ConstructL();
	AddViewL( view1 ); // transfer ownership to CAknViewAppUi
	CleanupStack::Pop(); // view1

	C$(Basename)View2* view2 = new (ELeave) C$(Basename)View2;

	CleanupStack::PushL( view2 );
	view2->ConstructL();
	AddViewL( view2 ); // transfer ownership to CAknViewAppUi
	CleanupStack::Pop(); // view2

	SetDefaultViewL(*view1);

	PrivacyStatementL();
	}

// ----------------------------------------------------
// C$(Basename)AppUi::~C$(Basename)AppUi()
// Destructor
// Frees reserved resources
// ----------------------------------------------------
//
C$(Basename)AppUi::~C$(Basename)AppUi()
	{
	delete iDecoratedTabGroup;
   }

// ------------------------------------------------------------------------------
// C$(Basename)AppUi::DynInitMenuPaneL(TInt aResourceId,CEikMenuPane* aMenuPane)
//  This function is called by the EIKON framework just before it displays
//  a menu pane. Its default implementation is empty, and by overriding it,
//  the application can set the state of menu items dynamically according
//  to the state of application data.
// ------------------------------------------------------------------------------
//
void C$(Basename)AppUi::DynInitMenuPaneL(
	TInt /*aResourceId*/,CEikMenuPane* /*aMenuPane*/)
	{
	}

// ----------------------------------------------------
// C$(Basename)AppUi::HandleKeyEventL(
//	 const TKeyEvent& aKeyEvent,TEventCode /*aType*/)
// takes care of key event handling
// ----------------------------------------------------
//
$if(series60!=1.x)
TKeyResponse C$(Basename)AppUi::HandleKeyEventL(
	const TKeyEvent& aKeyEvent,TEventCode aType)
	{
	if ( iTabGroup == NULL )
		{
		return EKeyWasNotConsumed;
		}

	if ( aKeyEvent.iCode == EKeyLeftArrow || aKeyEvent.iCode == EKeyRightArrow )
		{
		return iTabGroup->OfferKeyEventL( aKeyEvent, aType );
		}
	else
		{
		return EKeyWasNotConsumed;
		}
	}
$endif()
$if(series60==1.x)
TKeyResponse C$(Basename)AppUi::HandleKeyEventL(
	const TKeyEvent& aKeyEvent,TEventCode aType)
	{
	if ( iTabGroup == NULL )
		{
		return EKeyWasNotConsumed;
		}

	TInt active = iTabGroup->ActiveTabIndex();
	TInt count = iTabGroup->TabCount();

	switch ( aKeyEvent.iCode )
		{
		case EKeyLeftArrow:
			if ( active > 0 )
				{
				active--;
				iTabGroup->SetActiveTabByIndex( active );
				ActivateLocalViewL(TUid::Uid(iTabGroup->TabIdFromIndex(active)));
				}
			break;
		case EKeyRightArrow:
			if( (active + 1) < count )
				{
				active++;
				iTabGroup->SetActiveTabByIndex( active );
				ActivateLocalViewL(TUid::Uid(iTabGroup->TabIdFromIndex(active)));
				}
			break;
		default:
			return EKeyWasNotConsumed;
			break;
		}

	return EKeyWasConsumed;
	}
$endif()

// ----------------------------------------------------
// C$(Basename)AppUi::HandleCommandL(TInt aCommand)
// takes care of command handling
// ----------------------------------------------------
//
void C$(Basename)AppUi::HandleCommandL(TInt aCommand)
	{
	switch ( aCommand )
		{
		case EEikCmdExit:
			{
			Exit();
			break;
			}
		case E$(Basename)CmdAppTest:
			{
			iEikonEnv->InfoMsg(_L("test"));
			break;
			}
	case EHelp:
		{
		CArrayFix<TCoeHelpContext>* buf = CCoeAppUi::AppHelpContextL();
		HlpLauncher::LaunchHelpApplicationL(iEikonEnv->WsSession(), buf);
		}
		break;
	case EAbout:
		{
		CAknMessageQueryDialog* dlg = new (ELeave)CAknMessageQueryDialog(); 
		dlg->PrepareLC(R_ABOUT_QUERY_DIALOG);
		HBufC* title = iEikonEnv->AllocReadResourceLC(R_ABOUT_DIALOG_TITLE);
		dlg->QueryHeading()->SetTextL(*title);
		CleanupStack::PopAndDestroy(); //title
		HBufC* msg = iEikonEnv->AllocReadResourceLC(R_ABOUT_DIALOG_TEXT);
		dlg->SetMessageTextL(*msg);
		CleanupStack::PopAndDestroy(); //msg
		dlg->RunLD(); 
		}
		break;

		// TODO: Add Your command handling code here

		default:
			break;
		}
	}

$if(series60!=1.x)
 // ----------------------------------------------------
 // C$(Basename)AppUi::TabChangedL(TInt aIndex)
 // This method gets called when CAknTabGroup active 
 // tab has changed.
 // ----------------------------------------------------
 //
 void C$(Basename)AppUi::TabChangedL(TInt aIndex)
	 {
	 ActivateLocalViewL(TUid::Uid(iTabGroup->TabIdFromIndex(aIndex)));
	 }
$endif()

	CArrayFix<TCoeHelpContext>* C$(Basename)AppUi::HelpContextL() const
	{	 
	// Note: help will not work if the application uid3 is not in the
	// protected range.  The default uid3 range for projects created
	// from this template (0xE0000000 - 0xEFFFFFFF) are not in the protected range so they
	// can be self signed and installed on the device during testing.
	// Once you get your official uid3 from Symbian Ltd. and find/replace
	// all occurrences of uid3 in your project, the context help will
	// work.
	CArrayFixFlat<TCoeHelpContext>* ctxs = new(ELeave)CArrayFixFlat<TCoeHelpContext>(1);
	CleanupStack::PushL(ctxs);
	ctxs->AppendL(TCoeHelpContext(KUid$(Basename)App, KGeneral_Information));
	CleanupStack::Pop(ctxs);
	return ctxs;
	}
	
void C$(Basename)AppUi::PrivacyStatementL() 
	{
	// Note: to see privacy statement in emulator, copy
	// PrivacyStatement.txt from group/ directory to 
	// %EPOCROOT%\Epoc32\release\winscw\udeb\z\private\$(uidHexValue)\
	// Also note that on emulator you can't modify files on Z: drive,
	// so even if you answer Yes to privacy statement, it will popup
	// dialog every time you launch application. But on device it will work
	// as expected.
	HBufC * fileName = StringLoader::LoadLC(R_PRIVACY_STATEMENT_FILENAME);
	RFs &fs= iCoeEnv->FsSession();
	
	// Make full path to privacy statement
	TFileName fullFileName;
	TFileName privatePath;
	fs.PrivatePath(privatePath);
	TParse parser;
	TFileName processFileName(RProcess().FileName());
	User::LeaveIfError(parser.Set(*fileName, &privatePath, &processFileName));
	fullFileName = parser.FullName();
	CleanupStack::PopAndDestroy(fileName);
	
	if(BaflUtils::FileExists(fs, fullFileName)) 
		{
		RBuf text(C$(Basename)AppUi::ReadUnicodeFileL(fs, fullFileName));
		CleanupClosePushL(text);
		CAknMessageQueryDialog *dialog = CAknMessageQueryDialog::NewL(text);
		if(dialog->ExecuteLD(R_PRIVSTMT_DIALOG) == EAknSoftkeyYes) 
			{
			BaflUtils::DeleteFile(fs, fullFileName);
			}
		CleanupStack::PopAndDestroy(&text);
		}
	}

HBufC * C$(Basename)AppUi::ReadUnicodeFileL(RFs& aFs, const TDesC& aFileName)
	{
	RFile file;
	User::LeaveIfError(file.Open(aFs, aFileName, EFileShareReadersOnly | EFileStreamText | EFileRead));
	CleanupClosePushL(file);

	TInt size;
	User::LeaveIfError(file.Size(size));

	RBuf8 tmp;
	tmp.CreateL(size);
	CleanupClosePushL(tmp);
	User::LeaveIfError(file.Read(tmp));

	CCnvCharacterSetConverter * converter = CCnvCharacterSetConverter::NewLC();
	converter->PrepareToConvertToOrFromL(KCharacterSetIdentifierUtf8, aFs);

	HBufC *text = HBufC::NewL(size);

	TInt state = CCnvCharacterSetConverter::KStateDefault;
	TPtrC8 remainderOfForeignText(tmp);
	for(;;)
		{
		TPtr textPtr(text->Des());
		TInt retValue = converter->ConvertToUnicode(textPtr, remainderOfForeignText, state);
		if(retValue == CCnvCharacterSetConverter::EErrorIllFormedInput)
			User::Leave(KErrCorrupt);
		else if(retValue < 0)
			User::Leave(KErrGeneral);
		
		if(retValue == 0)
			break;
			
		remainderOfForeignText.Set(remainderOfForeignText.Right(retValue));
		}	
	
	CleanupStack::PopAndDestroy(converter);
	CleanupStack::PopAndDestroy(2);
	return text;
	}
	
// End of file
	